from django.utils.deprecation import MiddlewareMixin
from . import *
from log.publicLog import login_print


class LogMiddleware(object):
    """登陆日志"""
    def __init__(self, get_response):
        self.get_response = get_response
        # 这个中间件初始化的代码

    def __call__(self, request):
        # request到达view之前执行的代码
        try:
            username = str(request.user_obj.user_name)
        except:
            username = None
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']
        path = request.path
        method = request.method
        data = '用户[{}]访问:{}-{}-ip:{}'.format(
                username, method, path, ip
        )
        login_print(data)
        response = self.get_response(request)
        # response到达用户浏览器之前执行的代码
        # print('dengping:{}'.format(response))
        return response
